﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Core.Model;
using DapperExtensions;
using DapperExtensions.Mapper;
using log4net;

namespace DataServer.Dao
{
    public class EventDao : BaseDao<Event>
    {
        private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static EventMapper _eventMapper;

        public EventDao()
        {
            if (_eventMapper == null)
            {
                _eventMapper = new EventMapper();
            }
        }

        protected override string GetTableName()
        {
            if (_eventMapper != null)
                return _eventMapper.TableName;
            return "report_event";
        }

        public List<Event> GetEvents(EventType type, EventLevel level,bool? isConfirm, DateTime? from,DateTime? to)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                if(type != EventType.All)
                    predicateGroup.Predicates.Add(Predicates.Field<Event>(f => f.EventType, Operator.Eq, type));
                if(level!= EventLevel.All)
                    predicateGroup.Predicates.Add(Predicates.Field<Event>(f => f.EventLevel, Operator.Eq, level));
                if(isConfirm != null)
                    predicateGroup.Predicates.Add(Predicates.Field<Event>(f => f.IsConfirm, Operator.Eq, isConfirm));
                if(from!=null)
                    predicateGroup.Predicates.Add(Predicates.Field<Event>(f => f.EventTime, Operator.Ge, from));
                if(to!=null)
                    predicateGroup.Predicates.Add(Predicates.Field<Event>(f => f.EventTime, Operator.Le, to));

                IList<ISort> sort = new List<ISort>();
                sort.Add(new Sort { PropertyName = "EventTime", Ascending = false });
                IEnumerable<Event> devices = result?.Connection.GetList<Event>(predicateGroup, sort);
                return devices?.ToList();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

        public bool ConfirmEvent(string[] ids, string man)
        {
            if (ids == null || ids.Length == 0 || string.IsNullOrEmpty(man)) return false;
            ConnectResult result = null;
            try
            {
                StringBuilder sql =new StringBuilder( $"update {_eventMapper.TableName} set ConfirmTime='{DateTime.Now}',ConfirmMan='{man}',IsConfirm=1  where ");
                int size = ids.Length, index = 0;
                foreach (var id in ids)
                {
                    index++;
                    if (index < size)
                        sql.Append($" Id='{id}' or ");
                    else
                        sql.Append($" Id='{id}'");
                }   
                result = OpenDbConnection();
                result?.Connection.Update(sql.ToString());
                return true;

            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return false;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
            

        }
    }
    public sealed class EventMapper : ClassMapper<Event>
    {
        public EventMapper()
        {
            Table("report_event");
            Map(x => x.Id).Key(KeyType.Assigned);
            //Ignore this property entirely
            //optional, map all other columns
            AutoMap();
        }
    }
}
